<?php

namespace App\Extend;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * undocumented class
 *
 * @package default
 * @author
 **/
class Usdt
{
    protected $apiUrl = 'https://apilist.tronscanapi.com';
    protected $token = '9c735f73-623a-4496-ba18-92de14cea555';
    protected $address = 'TYjL99uwed1KvuteYt8dk6Qiqx7TSGHHo2';
    protected $contract_address = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';

    public function queryTransaction($transaction_quant, $transaction_day)
    {
        // 时区不同
        $start_timestamp = strtotime('-10 hours', strtotime($transaction_day)) * 1000;
        $end_timestamp = strtotime('+10 hours', strtotime($transaction_day)) * 1000;
        $params = [
            'contract_address' => $this->contract_address,
            'toAddress' => $this->address,
            'start_timestamp' => $start_timestamp,
            'end_timestamp' => $end_timestamp,
            'start' => 0,
            'limit' => 20
        ];
        Log::info('USDT查询参数：' . json_encode($params, JSON_UNESCAPED_UNICODE));
        $apiUrl = $this->apiUrl . '/api/token_trc20/transfers';
        $response = Http::withHeaders([
            'TRON-PRO-API-KEY' => $this->token
        ])->get($apiUrl, $params);
        $result = $response->json();
        if (!empty($result) && !empty($result['total'])) {
            foreach ($result['token_transfers'] as $item) {
                if ($item['contract_address'] != $this->contract_address || $item['to_address'] != $this->address) {
                    continue;
                }
                if (
                    $item['contractRet'] === 'SUCCESS'
                    && $item['finalResult'] === 'SUCCESS'
                    && $item['block'] > 0
                    && $item['status'] === 0
                    && $item['confirmed'] === true
                    && $item['revert'] === false
                    && (int)$item['quant'] === (int)$transaction_quant
                ) {
                    Log::info('USDT交易内容：' . json_encode($item, JSON_UNESCAPED_UNICODE));
                    return true;
                }
            }
        }
        return false;
    }
} // END class
